// const openID = require('openID')
// exports.main = async (event, context) => {
//     const { code, userInfo } = event
// 	const db = uniCloud.database()
// 	const user = db.collection('user')

//     // 获取openID
// 	const res = await openID(code)
	
// 	if(res.status === 200){
// 		const wx_openid = res.data.openid
// 		const wx_session_key = res.data.session_key
// 		//查询数据库判断用户是否已经注册
// 		const _user = await user.where({ openid: wx_openid }).get()
		
// 		if(_user.data && _user.data.length === 0){
// 			await user.add({
// 				avatarUrl: userInfo.avatar,
// 				nickName: userInfo.nickName,
// 				gender: userInfo.gender,
// 				openid: wx_openid,
// 				session_key: wx_session_key,
// 				mobile: '',
// 			})
// 		}else{
// 			// 用户存在更新session_key
// 			await user.where({ openid: wx_openid }).update({ 
// 				avatarUrl: userInfo.avatar,
// 				nickName: userInfo.nickName,
// 				gender: userInfo.gender,
// 				session_key: wx_session_key
// 			})
// 		}
// 		// 返回用户信息
// 		const info = await user.where({ openid: wx_openid }).field({
// 			avatarUrl: true,
// 			nickName: true,
// 			gender: true,
// 			mobile: true,
// 		}).get()
// 		return info
// 	}else{
// 		return res
// 	}
// }
// const openID = require('openID')
exports.main = async (event, context) => {
    const { userInfo, openid } = event
	const db = uniCloud.database()
	const user = db.collection('user')
	
	//查询数据库判断用户是否已经注册
	const _user = await user.where({ openid }).get()
	
	if(_user.data.length === 0){
		await user.add({
			avatarUrl: userInfo.avatar,
			nickName: userInfo.nickName,
			gender: userInfo.gender,
			mobile: '',
			openid
		})
	}else{
		// 用户存在更新session_key
		await user.where({ openid }).update({ 
			avatarUrl: userInfo.avatar,
			nickName: userInfo.nickName,
			gender: userInfo.gender
		})
	}
	// 返回用户信息
	const info = await user.where({ openid }).field({
		avatarUrl: true,
		nickName: true,
		gender: true,
		mobile: true,
	}).get()
	
	return info
}